package com.soul.parse;

/**
 * 替换文本中预定义标签
 */
public class ReplaceTag {

    //标签开始字符
    private String startTag;
    //标签结束字符
    private String endTag;
    //是否允许转义，允许则表示可以使用\保留标签内容
    private boolean enableTransfer = true;
    //替换处理接口
    private ReplaceHandler replaceHandler;

    /**
     * 全参数构造方法
     * @param startTag
     * @param endTag
     * @param enableTransfer
     * @param replaceHandler
     */
    public ReplaceTag(String startTag,String endTag,boolean enableTransfer,ReplaceHandler replaceHandler){
        this.enableTransfer = enableTransfer;
        this.startTag = startTag;
        this.endTag = endTag;
        this.replaceHandler = replaceHandler;
    }

    /**
     * 默认开启转义构造方法
     * @param startTag
     * @param endTag
     * @param replaceHandler
     */
    public ReplaceTag(String startTag,String endTag,ReplaceHandler replaceHandler){
        this.startTag = startTag;
        this.endTag = endTag;
        this.replaceHandler = replaceHandler;
    }

    /**
     * 替换的核心处理方法
     * @param text
     * @return
     */
    public String replace(String text){
        StringBuilder builder = new StringBuilder();
        if (text != null && text.length() > 0){
            char[] src = text.toCharArray();
            int offset = 0;
            int start = text.indexOf(startTag,offset);
            while (start > -1){
                if (enableTransfer && start > 0 && src[start - 1] == '\\'){
                    builder.append(src,offset,start - offset - 1).append(startTag);
                    offset = start + startTag.length();
                }else{
                    int end = text.indexOf(endTag,start);
                    if (end == -1){
                        builder.append(src,offset,src.length - offset);
                        offset = src.length;
                    }else {
                        builder.append(src,offset,start - offset);
                        offset = start + startTag.length();
                        String content = new String(src,offset,end - offset);
                        builder.append(replaceHandler.handler(startTag,content,endTag));
                        offset = end + endTag.length();
                    }
                }
                start = text.indexOf(startTag, offset);
            }
            if (offset < src.length) {
                builder.append(src, offset, src.length - offset);
            }
        }
        return builder.toString();
    }

    /**
     * 替换处理接口定义
     */
    @FunctionalInterface
    public interface ReplaceHandler{
        String handler(String startTag,String content,String endTag);
    }
    
}
